<?php
/* FILE: process_create.php
 * DESCRIPTION: Process called when a user presses the Submit button in newuser.php
 * 	- Creates a new user account
 * POST DATA: user_name, user_email, user_pass, user_question, user_answer
 * GET DATA: N/A
 */ 

// Inialize session
session_start();

// Include database connection settings
include('config.inc');

// Include functions
include('includes/functions.php');

$username = (string)$_POST['user_name'];
$email = (string)$_POST['user_email'];
$password = (string)$_POST['user_pass'];
$question = (string)$_POST['user_question'];
$answer = (string)$_POST['user_answer'];
//Set to display multiple errors if necessary
$errorUrl = '?';

//Make sure user name is valid
if(!validateUsername($username))
	$errorUrl = $errorUrl . 'unErr=2&';
	
// Retrieve user_name from database according to user's input
$loginQuery = "SELECT * FROM user WHERE (user_name = '" . mysql_real_escape_string($username) . "');";
if(!$login = mysql_query($loginQuery))
{
	die($loginQuery);
}
//Check to make sure email is not already in use
$emailCheck = "SELECT * FROM user WHERE (user_email = '" . mysql_real_escape_string($email) . "');";
if(!$emailCheckResult = mysql_query($emailCheck))
{
	die($emailCheck);
}

// Check user_name match
if (mysql_num_rows($login) > 0)
	$errorUrl = $errorUrl . 'unErr=1&';

// Make sure email is valid
if(!validateEmailAddress($email))
	$errorUrl = $errorUrl . 'emErr=1&';
	
// Make sure email is unique
if(mysql_num_rows($emailCheckResult) > 0)
	$errorUrl = $errorUrl . 'emErr=2&';

//Check to see if password is blank
if(trim($password) == "")
	$errorUrl = $errorUrl . 'pwErr=1&';

//Check to see if question is blank
if(trim($question) == "")
	$errorUrl = $errorUrl . 'sqErr=1&';
	
//Check to see if answer is blank
if(trim($answer) == "")
	$errorUrl = $errorUrl . 'saErr=1';

//No errors
if($errorUrl == '?')
{
	// Add user to database
	$addUserQuery =
		"INSERT INTO user (user_email, user_name, user_pass, user_last_login, user_join_date, user_security_question, user_security_answer) VALUES ('" 
		. mysql_real_escape_string($email) . 
		"','"
		. mysql_real_escape_string($username) .
		"','"
		. mysql_real_escape_string(md5($password)) . 
		"','"
		. mysql_real_escape_string($_SERVER['REQUEST_TIME']) .
		"','"
		. mysql_real_escape_string($_SERVER['REQUEST_TIME']) .
		"','"
		. mysql_real_escape_string($question) .
		"','"
		. mysql_real_escape_string($answer) .
		"')";
	if(!mysql_query($addUserQuery))
	{
		die($addUserQuery);
	}
	// Jump to secured page
	header('Location: index.php?err=createsuccess');
}
//Something went wrong
else
{
	header('Location: newuser.php' . $errorUrl);
}
?>